/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, message, Steps, Divider, Spin, InputNumber } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Area from '../../components/Area';
import DictCode from '../../components/DictCode';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { Step } = Steps;

@connect(({ loading, quosetprice }) => ({
  loading: loading.models.quosetprice,
  quosetprice,
  packList: quosetprice.packList,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const preQuoInfo = JSON.parse(window.localStorage.getItem('quotationadd'));
    const { dispatch } = this.props;
    // 获取产品信息
    dispatch({
      type: 'quosetprice/fetchProductAttr',
      payload: { preQuoInfo },
    }).then(response => {
      if (response.success) {
        if (preQuoInfo.packList && preQuoInfo.packList.length) {
          preQuoInfo.packList.map((_, index) => {
            this.getAreaPrice(index);
          });
        }
      }
    });
  }

  // 获取地区下产品建议售价
  getAreaPrice = (packIndex, priceId) => {
    // priceId存在表示选择地区，不存在即选择属性
    const { dispatch, packList } = this.props;
    let areaId = [];
    const matchList = [];
    if (
      packList[packIndex] &&
      packList[packIndex].priceList &&
      packList[packIndex].priceList.length
    ) {
      packList[packIndex].priceList.map(item => {
        if (priceId && item.id === priceId) {
          // 选择地区入口
          areaId = item.areaIdList;
        } else {
          // 选择属性入口
          areaId = [...areaId, ...(item.areaIdList || [])];
          areaId = [...new Set(areaId)];
        }
      });
    }
    if (
      packList[packIndex] &&
      packList[packIndex].listQuoPd &&
      packList[packIndex].listQuoPd.length
    ) {
      packList[packIndex].listQuoPd.map(pd => {
        const pdSpecifAttr = [];
        if (pd.pdAttrVOs && pd.pdAttrVOs.length) {
          pd.pdAttrVOs.map(attr => {
            pdSpecifAttr.push({
              attrId: attr.attrId,
              attrVal:
                (attr.attrValList && attr.attrValList.length && attr.attrValList.join(',')) || '',
            });
          });
        }
        matchList.push({
          pdId: pd.pdId,
          pdSpecifAttr,
        });
      });
    }
    if (priceId) {
      dispatch({
        type: 'quosetprice/fetchAreaPrice',
        payload: { areaId, matchList, packIndex, priceId },
      });
    } else if (packList[packIndex].priceList && packList[packIndex].priceList.length) {
      packList[packIndex].priceList.map(() => {
        dispatch({
          type: 'quosetprice/fetchAreaPrice',
          payload: { areaId, matchList, packIndex },
        });
      });
    }
  };

  // 计算税金
  getTaxMoney = (price, packIndex, priceId) => {
    // 输入的金额，包id, 价格列表id
    const {
      dispatch,
      quosetprice: { preQuoInfo },
      packList,
    } = this.props;
    const taxMoney = price * (preQuoInfo.taxRatio / 100) || 0;
    if (packList[packIndex].priceList && packList[packIndex].priceList.length) {
      packList[packIndex].priceList.map(item => {
        const temp = item;
        if (item.id === priceId) {
          temp.taxMoney = taxMoney;
          temp.quotePrice = price;
        }
      });
    }
    dispatch({
      type: 'quosetprice/updateModelData',
      payload: { packList },
    });
  };

  // 计算税率
  getTaxRate = (price, taxR) => {
    // 输入的，税率
    const {
      quosetprice: { preQuoInfo },
    } = this.props;
    // let x = 0;
    if (!preQuoInfo.serType) {
      message.warning('请先确定合同的服务类型，否则没法计算税率');
      return;
    }
    // } else if (serType == '2') {
    //   x = 0.06;
    // } else {
    //   x = 0.05;
    // }
    // let z = (price * (1 + taxR / 100)).toFixed(2); //   价税合计
    // let taxRate = ((z / (1 + x)) * x).toFixed(2); //税率
    const taxRate = Math.round(price * (taxR / 100) * 100) / 100;
    // eslint-disable-next-line consistent-return
    return taxRate;
  };

  // 更改执行地区设置地区数据
  async setAreaData(value, packIndex, priceId) {
    const { dispatch, packList } = this.props;
    if (packList[packIndex].priceList && packList[packIndex].priceList.length) {
      packList[packIndex].priceList.map(item => {
        const temp = item;
        if (item.id === priceId) {
          temp.areaIdList = value;
          temp.areaId = (value && value.length && value.join(',')) || '';
        }
      });
    }
    await dispatch({
      type: 'quosetprice/updateModelData',
      payload: { packList },
    });
    await this.getAreaPrice(packIndex, priceId);
  }

  // 删除地区
  delList = (packIndex, id) => {
    const { dispatch, packList } = this.props;
    packList[packIndex].priceList = packList[packIndex].priceList.filter(p => p.id !== id);
    dispatch({
      type: 'quosetprice/updateModelData',
      payload: { packList },
    });
  };

  //  下一步：提交数据
  submit = () => {
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll(err => {
      if (!err) {
        dispatch({
          type: 'quosetprice/submit',
        });
      }
    });
  };

  // 添加地区
  addList = packIndex => {
    const { dispatch, packList } = this.props;
    packList.map((item, index) => {
      if (index === packIndex) {
        packList[index].areaPriceId += 1;
        item.priceList.push({
          id: item.areaPriceId,
          areaIdList: [], // 地区id集合 【】
          areaId: '', // 地区id 全国为1
          quotePrice: 0, // 报价金额
          suggPrice: 0, // 建议售价
          taxMoney: 0, // 税金
        });
      }
    });
    dispatch({
      type: 'quosetprice/updateModelData',
      payload: { packList },
    });
  };

  // 取消选择执行地区
  async deSelectArea(value, packIndex, priceId) {
    // 选择的地区 ，包id, 价格列表id
    const { packList } = this.props;
    let setAreaList = []; // 设置重复地区
    if (packList[packIndex].priceList && packList[packIndex].priceList.length) {
      packList[packIndex].priceList.map(item => {
        if (priceId === item.id) {
          setAreaList = item.areaIdList.filter(v => v.key !== value.key);
        }
      });
    }
    this.setAreaData(setAreaList, packIndex, priceId);
  }

  // 选择执行地区
  async selectArea(value, packIndex, priceId) {
    // 选择的地区 ，包id, 价格列表id
    const { packList, form } = this.props;
    let areaList = []; // 当前包下所有地区
    let setAreaList = []; // 设置重复地区
    if (packList[packIndex].priceList && packList[packIndex].priceList.length) {
      packList[packIndex].priceList.map(item => {
        const selectedAreaList = item.areaIdList;
        if (priceId === item.id) {
          setAreaList = selectedAreaList;
        }
        areaList = [...areaList, ...selectedAreaList];
      });
    }
    if (areaList.indexOf(value) !== -1) {
      setTimeout(() => {
        form.setFieldsValue({
          [`priceList[${packIndex}][${priceId}][areaId]`]: setAreaList,
        });
      }, 0);
      message.warning('当前地区已选择，请重新选择！');
    } else {
      setAreaList = [...setAreaList, value];
    }
    this.setAreaData(setAreaList, packIndex, priceId);
  }

  // 产品属性更改
  async changeProAttr(value, packIndex, pdId, attrId) {
    // 属性值 包id 产品id 属性id
    const { dispatch, packList } = this.props;
    packList[packIndex].listQuoPd.map(pd => {
      const temp = pd;
      if (pd.pdId === pdId) {
        if (pd.pdAttrVOs && pd.pdAttrVOs.length) {
          pd.pdAttrVOs.map((attr, index) => {
            const obj = attr;
            if (attr.attrId === attrId) {
              obj.attrValList = value;
              temp.listAttr[index].attrValList = (value && value.length && value.join(',')) || '';
            }
          });
        }
      }
    });
    await dispatch({
      type: 'quosetprice/updateModelData',
      payload: { packList },
    });
    await this.getAreaPrice(packIndex);
  }

  // 渲染函数
  render() {
    const {
      loading,
      form: { getFieldDecorator },
      packList,
      quosetprice: { preQuoInfo },
      dispatch,
    } = this.props;
    return (
      <Form>
        <PageHeaderWrapper>
          <Spin tip="Loading..." spinning={loading}>
            <Card>
              <Steps current={1} style={{ marginBottom: 70 }}>
                <Step title="选择产品" />
                <Step title="设置价格" />
                <Step title="完成" />
              </Steps>
              {packList.map((pack, packIndex) => (
                // eslint-disable-next-line react/no-array-index-key
                <Card style={{ marginBottom: 16, border: '1px solid #e8e8e8' }} key={packIndex}>
                  {// 产品
                  pack.listQuoPd &&
                    pack.listQuoPd.map((pd, index) => (
                      <div key={pd.pdId}>
                        {index ? <Divider dashed /> : null}
                        <FormItem
                          label="产品名称"
                          labelCol={{ span: 2 }}
                          style={{ marginBottom: 10 }}
                        >
                          {getFieldDecorator(`name_${pd.pdId}_${packIndex}`, {
                            rules: [{ required: false, message: '请选择' }],
                          })(<div>{pd.pdName}</div>)}
                        </FormItem>
                        {pd.pdAttrVOs &&
                          pd.pdAttrVOs.map(attr => (
                            <FormItem
                              key={attr.attrId}
                              label={attr.attrName}
                              labelCol={{ span: 2 }}
                              wrapperCol={{ span: 10 }}
                              style={{ marginBottom: 10 }}
                            >
                              {getFieldDecorator(`pdAttr_${attr.attrId}_${packIndex}`, {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: attr.inputType === 5 && attr.attrValList,
                              })(
                                <DictCode
                                  inputType={
                                    // eslint-disable-next-line no-nested-ternary
                                    attr.inputType === 5 ? '2' : attr.inputType === 4 ? '1' : '3'
                                  }
                                  style={{ width: '100%' }}
                                  dictType={attr.dictType}
                                  onChange={value =>
                                    this.changeProAttr(value, packIndex, pd.pdId, attr.attrId)
                                  }
                                />
                              )}
                            </FormItem>
                          ))}
                      </div>
                    ))}
                  {pack.priceList && pack.priceList.length ? <Divider /> : null}
                  {// 定价
                  pack.priceList &&
                    pack.priceList.map((item, index) => (
                      <div key={item.id}>
                        {index ? <Divider dashed /> : null}
                        <div key={item.id}>
                          <FormItem
                            label="执行地区"
                            labelCol={{ span: 2 }}
                            wrapperCol={{ span: 10 }}
                            style={{ marginBottom: 20 }}
                          >
                            {getFieldDecorator(`priceList[${packIndex}][${item.id}][areaId]`, {
                              rules: [{ required: true, message: '请选择' }],
                              initialValue: item.areaIdList,
                            })(
                              <Area
                                labelInValue
                                style={{ width: 220 }}
                                isContainNation
                                mode="multiple"
                                onSelect={value => this.selectArea(value, packIndex, item.id)}
                                onDeselect={value => this.deSelectArea(value, packIndex, item.id)}
                              />
                            )}
                            {/* {index ? (
                              <a
                                style={{ marginLeft: 30 }}
                                onClick={e => {
                                  e.preventDefault();
                                  this.delList(packIndex, item.id);
                                }}
                              >
                                删除
                              </a>
                            ) : null} */}
                            {pack.priceList.length > 1 ? (
                              <a
                                style={{ marginLeft: 30 }}
                                onClick={e => {
                                  e.preventDefault();
                                  this.delList(packIndex, item.id);
                                }}
                              >
                                删除
                              </a>
                            ) : null}
                          </FormItem>
                          <FormItem
                            label="报价金额"
                            labelCol={{ span: 2 }}
                            wrapperCol={{ span: 10 }}
                            style={{ marginBottom: 20 }}
                          >
                            {getFieldDecorator(`priceList[${packIndex}][${item.id}][quotePrice]`, {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入小数点不超过2位的数字',
                                  pattern: /^-?\d+\.?\d{0,2}$/,
                                },
                              ],
                            })(
                              <InputNumber
                                min={0}
                                max={9999999.99}
                                placeholder="请输入"
                                style={{ width: '100px' }}
                                onChange={value => this.getTaxMoney(value, packIndex, item.id)}
                              />
                            )}
                            <span>（建议售价：{item.suggPrice}）</span>
                          </FormItem>
                          {preQuoInfo.taxRatio && (
                            <FormItem
                              label="税金"
                              labelCol={{ span: 2 }}
                              wrapperCol={{ span: 10 }}
                              style={{ marginBottom: 20 }}
                            >
                              {getFieldDecorator(`priceList[${packIndex}][${item.id}][taxMoney]`, {
                                rules: [{ required: false, message: '请选择' }],
                                initialValue: item.taxMoney,
                              })(<InputNumber style={{ width: '100px' }} precision={2} disabled />)}
                              <span>（税率：{preQuoInfo.taxRatio}%）</span>
                            </FormItem>
                          )}
                        </div>
                      </div>
                    ))}
                  <FormItem
                    label="&nbsp;"
                    colon={false}
                    labelCol={{ span: 2 }}
                    wrapperCol={{ span: 10 }}
                  >
                    <Button
                      style={{ width: 220, textAlign: 'center' }}
                      type="dashed"
                      icon={<PlusOutlined />}
                      onClick={() => this.addList(packIndex)}
                    >
                      添加地区
                    </Button>
                  </FormItem>
                </Card>
              ))}
              <div style={{ marginTop: 50, marginBottom: 30, textAlign: 'center' }}>
                <Button
                  style={{ marginRight: 30 }}
                  size="large"
                  onClick={() => {
                    dispatch({
                      type: 'quosetprice/updateModelData',
                      payload: {
                        isGoBack: true,
                      },
                    });
                    router.push(`/salemanage/quotation/add`);
                  }}
                >
                  上一步
                </Button>
                <Button type="primary" size="large" onClick={this.submit}>
                  提交
                </Button>
              </div>
            </Card>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default BasicForm;
